package com.ruoyi.edh.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.CouponException;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.ShippingTemplateException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberingGetUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.edh.domain.*;
import com.ruoyi.edh.domain.dto.EdhOrderGoodsDto;
import com.ruoyi.edh.domain.dto.EdhShippingGoodsDto;
import com.ruoyi.edh.mapper.*;
import com.ruoyi.edh.service.IEdhMasterOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


/**
 * 易订货-主订单Service业务层处理
 *
 * @author xxx
 * @date 2020-09-02
 */
@Service
public class EdhMasterOrderServiceImpl implements IEdhMasterOrderService
{
    @Autowired
    private EdhMasterOrderMapper edhMasterOrderMapper;
    //订单
    @Autowired
    private EdhOrderMapper edhOrderMapper;
    //商品详情实体类
    @Autowired
    private EdhGoodsSpecificationsMapper edhGoodsSpecificationsMapper;
    //商品优惠卷实体类
    @Autowired
    private EdhCouponMapper edhCouponMapper;
    //我的优惠卷
    @Autowired
    private EdhCouponLogMapper edhCouponLogMapper;
    //商品
    @Autowired
    private EdhGoodsMapper edhGoodsMapper;
    //地址
    @Autowired
    private EdhShoppingAddressMapper edhShoppingAddressMapper;
    //运费模版
    @Autowired
    private EdhShippingTemplateMapper edhShippingTemplateMapper;
    //供应商
    @Autowired
    private EdhSupplierMapper edhSupplierMapper;
    // 购物车mapper
    @Autowired
    private EdhShoppingCartMapper shoppingCartMapper;
    /**
     * 查询易订货-主订单
     *
     * @param id 易订货-主订单ID
     * @return 易订货-主订单
     */
    @Override
    public EdhMasterOrder selectEdhMasterOrderById(Long id)
    {
        return edhMasterOrderMapper.selectEdhMasterOrderById(id);
    }

    /**
     * 查询易订货-主订单列表
     *
     * @param edhMasterOrder 易订货-主订单
     * @return 易订货-主订单
     */
    @Override
    public List<EdhMasterOrder> selectEdhMasterOrderList(EdhMasterOrder edhMasterOrder)
    {
        return edhMasterOrderMapper.selectEdhMasterOrderList(edhMasterOrder);
    }

    /**
     * 新增易订货-主订单
     *
     * @param edhMasterOrder 易订货-主订单
     * @return 结果
     */
    @Override
    public int insertEdhMasterOrder(EdhMasterOrder edhMasterOrder)
    {
        edhMasterOrder.setCreateTime(DateUtils.getNowDate());
        return edhMasterOrderMapper.insertEdhMasterOrder(edhMasterOrder);
    }

    /**
     * 修改易订货-主订单
     *
     * @param edhMasterOrder 易订货-主订单
     * @return 结果
     */
    @Override
    public int updateEdhMasterOrder(EdhMasterOrder edhMasterOrder)
    {
        edhMasterOrder.setUpdateTime(DateUtils.getNowDate());
        return edhMasterOrderMapper.updateEdhMasterOrder(edhMasterOrder);
    }

    /**
     * 批量删除易订货-主订单
     *
     * @param ids 需要删除的易订货-主订单ID
     * @return 结果
     */
    @Override
    public int deleteEdhMasterOrderByIds(String[] ids)
    {

        // 子订单状态设置为已取消
        edhOrderMapper.updateOrdersStatusToCancel(ids);
        return edhMasterOrderMapper.deleteEdhMasterOrderByIds(ids);
    }

    /**
     * 删除易订货-主订单信息
     *
     * @param id 易订货-主订单ID
     * @return 结果
     */
    @Override
    public int deleteEdhMasterOrderById(Long id)
    {
        return edhMasterOrderMapper.deleteEdhMasterOrderById(id);
    }

    /**
     * 添加购买后订单逻辑
     * @param edhOrderGoodsDto
     * @return
     * @throws CouponException
     * @throws ShippingTemplateException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public EdhMasterOrder addShippingOrder(EdhOrderGoodsDto edhOrderGoodsDto) throws CouponException, ShippingTemplateException {
        Boolean add=true;

        //获取用户id
        Long userId = SecurityUtils.getUserId();

        // 删除购物车商品
        List<Long> goodsIds = new ArrayList<Long>();
        edhOrderGoodsDto.getShippingGoodsDtoList().forEach(orderGoods->{
            goodsIds.add( orderGoods.getGoodsSpecificationsId() );
        });
        shoppingCartMapper.deleteByUserIdAndGoodsId(userId,goodsIds);

        //未优惠总价价格
        BigDecimal notDiscounted=new BigDecimal(0);
        //优惠后总价
        BigDecimal sum=new BigDecimal(0);
        BigDecimal shippingSum=new BigDecimal(0);
        //获取购买订单商品的列表
        List<EdhShippingGoodsDto> shippingGoodsDtoList = edhOrderGoodsDto.getShippingGoodsDtoList();
        //循环需要添加订单的商品集合
        for (EdhShippingGoodsDto edhShipping : shippingGoodsDtoList) {
            //获取购买商品的商品规格信息
            EdhGoodsSpecifications edhGoodsSpecifications = edhGoodsSpecificationsMapper.selectEdhGoodsSpecificationsById(edhShipping.getGoodsSpecificationsId());
            //获得商品单价
            BigDecimal shopPrice = edhGoodsSpecifications.getShopPrice();
            //获得商品购买数量
            BigDecimal quantity = BigDecimal.valueOf(edhShipping.getQuantity());
            //获得商品总价格
            BigDecimal multiply = shopPrice.multiply(quantity);
            //计入本次购买总价
            sum=sum.add(multiply);
            notDiscounted=notDiscounted.add(multiply);
            //查询商品信息
            EdhGoods edhGoods = edhGoodsMapper.selectEdhGoodsById(edhShipping.getId());
            if (edhGoodsSpecifications.getStoreCount() - edhShipping.getQuantity() < 0) {
                throw new CustomException("商品库存不足");
            }
            //下完订单减少商品库存
            edhGoodsSpecificationsMapper.lessStoreCount(edhShipping.getQuantity(),edhGoodsSpecifications.getId());
            //根据订单总价，和供应商信息查询运费信息
            EdhShippingTemplate edhShippingTemplate = edhShippingTemplateMapper.selectShippingAmount(edhGoods.getSupplierId(), multiply.toString());
         /*   if (null==edhShippingTemplate){
                throw  new ShippingTemplateException("商品运费发生异常");
            }
            shippingSum=shippingSum.add(edhShippingTemplate.getShipping());*/
            if (null!=edhShippingTemplate){
                shippingSum=shippingSum.add(edhShippingTemplate.getShipping());
            }

        }
        //设置优惠卷类型
        Integer type=0;
        //优惠卷属性
        EdhCoupon edhCoupon=null;
        //我的优惠卷
        EdhCouponLog edhCouponLog=null;
        if (StringUtils.isNotNull(edhOrderGoodsDto.getCouponId()) && edhOrderGoodsDto.getCouponId()!=0){


            //获得优惠卷对象
            edhCouponLog = edhCouponLogMapper.selectOneEdhCouponLogById(edhOrderGoodsDto.getCouponId(),userId);
            if (null==edhCouponLog){
                throw new CouponException("找不到优惠卷");
            }
            if (edhCouponLog.getStatus()!=0){
                throw new CouponException("优惠卷已使用或者已过期");
            }
            edhCoupon = edhCouponMapper.selectEdhCouponById(edhCouponLog.getCouponId());
        Integer status = edhCoupon.getStatus();
     /*   if (2!=status){
            throw new CouponException("优惠卷未生效");
        }*/
            //获得当前时间毫秒数
        long time = System.currentTimeMillis();
        //获取优惠卷使用开始时间毫秒数
        long startTime = edhCouponLog.getUseStartTime().getTime();
        long endTime = edhCouponLog.getUseEndTime().getTime();
        if (startTime>time||endTime<time){
            throw new CustomException("优惠卷已超出使用时间");
        }
        //获得优惠卷类型
         type = Integer.parseInt(edhCoupon.getType());
        switch (type){
            //满减优惠卷
            case 1:{
                BigDecimal condition = edhCoupon.getCondition();
                int i = sum.compareTo(condition);
                //订单金额小于优惠卷金额抛出异常
                if (-1==i){
                    throw new CustomException("订单达不到使用优惠卷额度");
                }
                //计算使用优惠后的金额
                sum=sum.subtract(edhCoupon.getMoney());
                break;
            }
            //折扣优惠卷
            case 2:{
                sum=sum.multiply(edhCoupon.getMoney());
                break;
            }
            case 3:{
                sum=sum.subtract(edhCoupon.getMoney());
                break;
            }
            default:
                break;
        }

        }
        EdhShoppingAddress edhShoppingAddress = edhShoppingAddressMapper.selectEdhShoppingAddressById(edhOrderGoodsDto.getAddressId());
        if (null==edhShoppingAddress){
            throw new CustomException("找不到当前选中的收货地址");
        }
        //设置主订单信息
        EdhMasterOrder edhMasterOrder=new EdhMasterOrder();
        //生成主订单id
        String zd = NumberingGetUtils.numberingGet("zd");
        edhMasterOrder.setMasterOrderNo(zd);
        edhMasterOrder.setAddressId(edhOrderGoodsDto.getAddressId().toString());
        edhMasterOrder.setAddressPhone(edhShoppingAddress.getPhone());
        edhMasterOrder.setAddressUsername(edhShoppingAddress.getUsername());
        edhMasterOrder.setAddressDetails(edhShoppingAddress.getCoordinate().replace(",","")+edhShoppingAddress.getAddress());
        edhMasterOrder.setOrderAmount(notDiscounted);
        // 如果金额小于0 则 设置为0.01元
        if (1 != sum.compareTo(new BigDecimal(0))){
            sum = new BigDecimal(0.01);
        }
        edhMasterOrder.setActualAmount(sum);
        edhMasterOrder.setShipping(shippingSum);
        edhMasterOrder.setMicroshopId(edhOrderGoodsDto.getMicroshopId()!=null?edhOrderGoodsDto.getMicroshopId():null);
        edhMasterOrder.setUserId(userId.toString());
        if (null!=edhCoupon){
            edhMasterOrder.setCouponId(edhOrderGoodsDto.getCouponId().toString());
            edhMasterOrder.setCouponAmount(edhCoupon.getMoney().toString());
        }
        //主订单添加
        int masterOrder = edhMasterOrderMapper.insertEdhMasterOrder(edhMasterOrder);
        if (1<masterOrder){
            add=false;
        }
        //判断商品有无使用优惠卷
        if (type!=0) {
            edhCouponLog.setUseTime(new Date());
            edhCouponLog.setStatus(1);
            //修改优惠卷变成已使用
            int coupon = edhCouponLogMapper.updateEdhCouponLog(edhCouponLog);
            if (1 < coupon) {
                add = false;
            }
        }

        //循环购买商品列表
        for (EdhShippingGoodsDto edhShippingGoodsDto : shippingGoodsDtoList) {
            //获取购买商品的商品规格信息
            EdhGoodsSpecifications edhGoodsSpecifications = edhGoodsSpecificationsMapper.selectEdhGoodsSpecificationsById(edhShippingGoodsDto.getGoodsSpecificationsId());
            //获得商品单价
            BigDecimal shopPrice = edhGoodsSpecifications.getShopPrice();
            //获得商品购买数量
            BigDecimal quantity = BigDecimal.valueOf(edhShippingGoodsDto.getQuantity());
            //获得商品总价格
            BigDecimal multiply = shopPrice.multiply(quantity);
            //创建子订单对象
            EdhOrder edhOrder=new EdhOrder();
            edhOrder.setMicroshopId(edhOrderGoodsDto.getMicroshopId()!=null?edhOrderGoodsDto.getMicroshopId():null);
            edhOrder.setOrderNo(NumberingGetUtils.numberingGet("dd"));
            edhOrder.setShipName(edhShoppingAddress.getUsername());
            edhOrder.setShipPhone(edhShoppingAddress.getPhone());
            edhOrder.setShipAddress(edhShoppingAddress.getCoordinate()+edhShoppingAddress.getAddress());
            edhOrder.setMasterOrderId(edhMasterOrder.getId().toString());
            edhOrder.setGoodsId(edhShippingGoodsDto.getId().toString());
            edhOrder.setGoodsPrice(edhGoodsSpecifications.getShopPrice());
            edhOrder.setGoodsNumber(edhShippingGoodsDto.getQuantity());
            edhOrder.setOrderAmount(multiply);
            //判断商品有无使用优惠卷
            if (type!=0){
                //计算商品实付价格
                if (type==2){
                    multiply=multiply.multiply(edhCoupon.getMoney());
                }else {
                    BigDecimal divide = sum.divide(multiply, 5, BigDecimal.ROUND_HALF_UP);
                    multiply=multiply.multiply(divide).setScale(2,BigDecimal.ROUND_HALF_UP);
                }
            }

            edhOrder.setActualAmount(multiply);
            edhOrder.setPaymentStatus("0");
            //查询商品信息
            EdhGoods edhGoods = edhGoodsMapper.selectEdhGoodsById(edhGoodsSpecifications.getGoodsId());
            //根据订单总价，和供应商信息查询运费信息
            EdhShippingTemplate edhShippingTemplate = edhShippingTemplateMapper.selectShippingAmount(edhGoods.getSupplierId(), multiply.toString());
        /*    if (null==edhShippingTemplate){
                throw  new ShippingTemplateException("商品运费发生异常");
            }*/
          if (null!=edhShippingTemplate){
              //设置单笔运费
              edhOrder.setShipping(edhShippingTemplate.getShipping());
            }else{
              edhOrder.setShipping(new BigDecimal(0));
          }
            //查询供应商信息
            EdhSupplier edhSupplier = edhSupplierMapper.selectEdhSupplierById(edhGoods.getSupplierId());
            if (null==edhSupplier){
                throw new CustomException("找不到供应商信息");
            }

            edhOrder.setUserId(userId.toString());
            edhOrder.setGoodsName(edhGoods.getTitle());
            edhOrder.setGoodsSupplierName(edhSupplier.getName());
            edhOrder.setGoodsImage(edhGoods.getImage());
            edhOrder.setGoodsSpecificationsId(edhShippingGoodsDto.getGoodsSpecificationsId().toString());
            edhOrder.setGoodsSpecifications(edhGoodsSpecifications.getSpecifications());
            //添加子订单
            int order = edhOrderMapper.insertEdhOrder(edhOrder);
            if (1<order){
                add=false;
            }
        }

        return edhMasterOrder;
    }
}
